package com.grm.exception;

import com.alibaba.fastjson.JSON;
import com.grm.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice(annotations = { RestController.class })
@Slf4j
public class GlobalExceptionHandler
{
    @ExceptionHandler({ BusinessException.class })
    public Result businessExceptionHandler(HttpServletRequest servletRequest,Exception e) {
        BusinessException exception = (BusinessException) e;
        log.error("businessException : {}", e.getMessage());
        return Result.failed(exception.getCode(),exception.getMessage());
    }

    @ExceptionHandler({ MethodArgumentNotValidException.class })
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {

        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> errorMessageList = new ArrayList<>();
        fieldErrors.stream().forEach(x->errorMessageList.add(x.getDefaultMessage()));
        log.error("MethodArgumentNotValidException : {}", JSON.toJSONString(errorMessageList));
        return Result.failed(JSON.toJSONString(errorMessageList));
    }
}
